package com.chinaunicom.server.controller;

import com.chinaunicom.server.service.LoginService;
import com.chinaunicom.server.util.AppConstant;
import com.chinaunicom.server.util.CookieUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: ruiyanglee
 * @date: 2020-09-15 09:58
 * @description:
 */

@RestController
@RequestMapping("/user")
public class UserController {

    public static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private LoginService loginService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    // 登录
    @ResponseBody
    @GetMapping("/login")
    public Object login(String username, String password, String originalUrl,
                        HttpServletRequest request, HttpServletResponse response) {
        boolean loginSuccess = loginService.login(username, password);
        if (loginSuccess) {
            // 取到客户端唯一标识
            String uuid = CookieUtil.getCookie(request, "uuid");
            //创建ticket
            String ticket = loginService.createTicket(uuid);
            // 将ticket票据传递到app1
            CookieUtil.setCookie(response, "ticket", ticket, AppConstant.REDIS_TICKET_ALIVE_SECONDS);
            log.info("ticket {}",ticket);
            //将登录票据存储到redis,测试60秒过期
            redisTemplate.opsForValue().set(AppConstant.REDIS_TICKET_PREFIX + ticket, username, AppConstant.REDIS_TICKET_ALIVE_SECONDS, TimeUnit.SECONDS);
            //回源url
//            String originalUrl = CookieUtil.getCookie(request, "originalUrl");
            log.info("originUrl {}", originalUrl);
            try {
                //重定向到源url
                response.sendRedirect(originalUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ticket;
        }
        return "login fail ";
    }

    /**
     * 退出登录
     * @param ticket
     * @return
     */
    @ResponseBody
    @RequestMapping("/logout")
    public boolean logout(String ticket){
        return redisTemplate.delete(AppConstant.REDIS_TICKET_PREFIX+ticket);
    }

    /**
     * 检查ticket
     *
     * @param ticket ticket
     * @param uuid   客户端唯一标识
     */
    @ResponseBody
    @RequestMapping("/checkTicket")
    public String checkTicket(String ticket, String uuid) {

        log.info("check ticket {}",ticket);
        String oldTicketValue = redisTemplate.opsForValue().get(AppConstant.REDIS_TICKET_PREFIX + ticket);
        //较验ticket
        //当redis存在ticket时验证成功
        if (ticket != null && oldTicketValue != null ) {
            //开启一次性ticket,每次返回新ticket，增强安全性，但是性能会降低
            //注意：开启一次性ticket验证时，uuid和ticket必传
            if(AppConstant.ENABLE_DISPOSABLE_TICKET) {
                //清除旧的ticket
                redisTemplate.delete(AppConstant.REDIS_TICKET_PREFIX + ticket);
                //生成新的ticket
                String newTicket = loginService.createTicket(uuid);
                //保存新的ticket
                redisTemplate.opsForValue().set(AppConstant.REDIS_TICKET_PREFIX + newTicket, oldTicketValue, AppConstant.REDIS_TICKET_ALIVE_SECONDS, TimeUnit.SECONDS);
                //返回新ticket
                return newTicket;
            }else {
                return ticket;
            }
        } else return null;
    }

    /**
     * 获取用户信息
     *
     * @param ticket ticket
     */
    @RequestMapping("/getUserInfo")
    public Map<String, String> getUserInfo(String ticket) {
        //模拟根据ticket获取用户用户名,根据用户名获取用户信息
        String userName = redisTemplate.opsForValue().get(AppConstant.REDIS_TICKET_PREFIX + ticket);
        if (StringUtils.isEmpty(userName)) {
            return null;
        }
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("username", userName);
        userInfo.put("ticket", ticket);
        return userInfo;
    }

    @RequestMapping("/loginPage")
    public Object loginPage(String originalUrl, String uuid, HttpServletRequest request, HttpServletResponse response) throws IOException {
        CookieUtil.getCookie(request, "uuid");
        CookieUtil.setCookie(response, "originalUrl", originalUrl, AppConstant.REDIS_TICKET_ALIVE_SECONDS);
        log.info("original url {}",originalUrl);
        // 模拟页面请求登录过程
        login( "leeyu",  "leeyu",originalUrl, request,  response);
        return "ticket";
    }
}
